import React, { createContext, useContext, useState, ReactNode } from 'react';
import { useApiSettings } from './ApiSettingsContext';

export interface ChatMessage {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: number;
}

export interface Reference {
  id: string;
  title: string;
  content: string;
  source: string;
  relevanceScore: number;
  metadata: Record<string, any>;
}

interface ChatContextType {
  messages: ChatMessage[];
  sendMessage: (content: string) => Promise<void>;
  loading: boolean;
  references: Reference[];
  showReferences: boolean;
  toggleReferences: () => void;
  clearChat: () => void;
}

const ChatContext = createContext<ChatContextType | undefined>(undefined);

export const ChatProvider: React.FC<{children: ReactNode}> = ({ children }) => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [loading, setLoading] = useState(false);
  const [references, setReferences] = useState<Reference[]>([]);
  const [showReferences, setShowReferences] = useState(true);
  const { apiSettings } = useApiSettings();

  const toggleReferences = () => {
    setShowReferences(prev => !prev);
  };

  const clearChat = () => {
    setMessages([]);
    setReferences([]);
  };

  const sendMessage = async (content: string) => {
    if (!content.trim()) return;
    
    // 添加用户消息
    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      role: 'user',
      content,
      timestamp: Date.now(),
    };
    
    setMessages(prev => [...prev, userMessage]);
    setLoading(true);
    
    try {
      // 实际项目中这里应该调用实际的API
      // 以下是模拟响应
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 模拟AI回复和参考资料
      const aiMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: `这是对问题"${content}"的回答。可以自由引用知识库中的信息，并且提供引用来源。`,
        timestamp: Date.now(),
      };
      
      // 模拟参考资料
      const mockReferences: Reference[] = [
        {
          id: 'ref1',
          title: '相关文档1',
          content: '这是一段与用户问题相关的内容，它来自于知识库中的一篇文档。',
          source: 'https://example.com/doc1',
          relevanceScore: 0.89,
          metadata: {
            fileName: 'doc1.pdf',
            date: '2023-05-10',
            author: '张三'
          }
        },
        {
          id: 'ref2',
          title: '相关文档2',
          content: '这是另一段相关内容，它提供了更多补充信息。',
          source: 'https://example.com/doc2',
          relevanceScore: 0.75,
          metadata: {
            url: 'https://example.com/doc2',
            date: '2023-06-15'
          }
        }
      ];
      
      setMessages(prev => [...prev, aiMessage]);
      setReferences(mockReferences);
    } catch (error) {
      console.error('Error sending message:', error);
      // 添加错误消息
      const errorMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: '抱歉，处理您的请求时出现错误。请稍后再试。',
        timestamp: Date.now(),
      };
      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <ChatContext.Provider 
      value={{ 
        messages, 
        sendMessage, 
        loading, 
        references, 
        showReferences, 
        toggleReferences,
        clearChat
      }}
    >
      {children}
    </ChatContext.Provider>
  );
};

export const useChatContext = () => {
  const context = useContext(ChatContext);
  if (context === undefined) {
    throw new Error('useChatContext must be used within a ChatProvider');
  }
  return context;
}; 